//
//  UIButton+Additions.swift
//  live
//
//  Created by melvyn on 2018/8/16.
//  Copyright © 2018 NEET. All rights reserved.
//

import Foundation

extension UIButton {
    enum ImageLayoutAttribute {
        case top
        case left
        case bottom
        case right
    }
    
    func applyImageLayout(withAttribute attribute: ImageLayoutAttribute, fixedSpacing: CGFloat) {
        assert(imageView != nil && titleLabel != nil, "")
        
        setNeedsLayout()
        
        let imageSize = imageView!.frame.size
        let textSize = titleLabel!.frame.size
        
        var imageEdgeInsets: UIEdgeInsets = .zero
        var titleEdgeInsets: UIEdgeInsets = .zero
        
        switch attribute {
        case .top:
            imageEdgeInsets = UIEdgeInsets(top: -textSize.height - fixedSpacing / 2, left: 0, bottom: 0, right: -textSize.width)
            titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageSize.width, bottom: -imageSize.height - fixedSpacing / 2.0, right: 0)
        case .left:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: -fixedSpacing / 2.0, bottom: 0, right: fixedSpacing / 2.0)
            titleEdgeInsets = UIEdgeInsets(top: 0, left: fixedSpacing / 2.0, bottom: 0, right: -fixedSpacing / 2.0)
        case .bottom:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -textSize.height - fixedSpacing / 2.0, right: -textSize.width)
            titleEdgeInsets = UIEdgeInsets(top: -imageSize.height - fixedSpacing / 2.0, left: -imageSize.width, bottom: 0, right: 0)
        default:
            imageEdgeInsets = UIEdgeInsets(top: 0, left: imageSize.width + fixedSpacing / 2.0, bottom: 0, right: -textSize.width - fixedSpacing / 2.0)
            titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageSize.width - fixedSpacing / 2.0, bottom: 0, right: imageSize.width + fixedSpacing / 2.0)
        }
        
        self.imageEdgeInsets = imageEdgeInsets
        self.titleEdgeInsets = titleEdgeInsets
        setNeedsLayout()
    }
}
